//需求1:  渲染学员信息

//发送axios 请求数据
function initStuList() {
  axios({
    url: "/student/list",
    method: "get",
  }).then(({ data: res }) => {
    //判断是否获取数据成功
    if (res.code == 0) {
      //渲染数据
      let arr = res.data
        .map(
          (ele) => `
      <tr>
      <th scope="row">${ele.id}</th>
      <td>${ele.name}</td>
      <td>${ele.age}</td>
      <td>${ele.sex}</td>
      <td>${ele.group}</td>
      <td>${ele.phone}</td>
      <td>${ele.salary}</td>
      <td>${ele.truesalary}</td>
      <td>${ele.province + ele.city + ele.county}</td>
      <td>
    <button type="button" class="update  btn btn-primary btn-sm"  data-bs-toggle="modal"  data-bs-target="#updateModal"
    data-id="${ele.id}"> 修改
        </button>
        <button type="button"  class="delete btn btn-danger btn-sm"  data-id="${
          ele.id
        }">删除</button>
      </td>
    </tr> `
        )
        .join("");
      document.querySelector("tbody").innerHTML = arr;
    }
  });
}
//调用函数
initStuList();

//需求2:删除功能
//动态新增加的元素需要用事件委托,给父盒子注册点击事件,委托给子元素处理
let tbody = document.querySelector("tbody");
tbody.onclick = function (e) {
  if (!e.target.classList.contains("delete")) return;
  if (!confirm("确定要删除吗")) return;
  //获取id
  let id = e.target.getAttribute("data-id");
  //发送axios请求  删除数据
  axios({
    url: "/student/delete",
    method: "delete",
    params: { id },
  }).then(({ data: res }) => {
    //console.log(res);
    //判断业务状态码
    if (res.code == 0) {
      //成功给提示
      toastr.success("删除信息成功");
      //重新渲染页面
      initStuList();
    }
  });
};

//需求3:省市区三级联动
//获取元素
let updateForm = document.querySelector(".update-form");
let addForm = document.querySelector(".add-form");
//调用函数
initprovince(updateForm);
initprovince(addForm);

//需求3:省市区三级联动
function initprovince(form) {
  let province = form.querySelector('[name="province"]');
  //发送axios
  axios({
    url: "/geo/province",
    method: "get",
  }).then(({ data: res }) => {
    //成功回调
    // console.log(res);
    let arr = res
      .map((ele) => `<option  value="${ele}">${ele}</option>`)
      .join("");
    //方法1:
    //arr.unshift(` <option selected value="">--省--</option>`);
    //方法2:
    province.innerHTML += arr;
  });

  //市级
  let city = form.querySelector('[name="city"]');
  province.onchange = function () {
    county.innerHTML = `<option selected value="">--县--</option>`;
    if (province.value == "") {
      city.innerHTML = `<option selected value="">--市--</option>`;
      return;
    }
    //发送axios
    axios({
      url: "/geo/city",
      method: "get",
      //data: { 'post请求参数'},
      params: { pname: this.value },
    }).then(({ data: res }) => {
      //成功回调
      // console.log(res)
      let arr = res
        .map((ele) => `<option  value="${ele}">${ele}</option>`)
        .join("");
      city.innerHTML += arr;
    });
  };

  //县级
  let county = form.querySelector('[name="county"]');
  city.onchange = function () {
    if (this.value == "") {
      county.innerHTML = `<option selected value="">--县--</option>`;
      return;
    }
    axios({
      url: "/geo/county",
      method: "get",
      // data: { 'post请求参数'},
      params: { pname: province.value, cname: city.value },
    }).then(({ data: res }) => {
      //成功回调
      // console.log(res)
      let arr = res
        .map((ele) => `<option  value="${ele}">${ele}</option>`)
        .join("");
      county.innerHTML = arr;
    });
  };
}

//需求4:添加学生信息
addForm.onsubmit = function (e) {
  //阻止表单默认跳转
  e.preventDefault();
  //发送axios请求数据
  axios({
    url: "/student/add",
    method: "post",
    //获取表单中数据
    data: $(this).serialize(),
    //params: { 'get请求参数'}
  }).then(({ data: res }) => {
    if (res.code == 0) {
      toastr.success("恭喜你添加数据成功");
      //删除成功,就要关闭对话框
      document.querySelector("#addModal .btn-close").click();
      //刷新页面
      initStuList();
    }
    //成功回调
    // console.log(res);
  });
};

//需求5: 点击按钮.发送axios 请求 渲染用户信息(事件委托)
//这里需要用 addEventListener  注册事件  直接用onclick()  会覆盖上的面的
document.querySelector("tbody").addEventListener("click", function (e) {
  if (!e.target.classList.contains("update")) return;
  //自定义属性 获取id
  let id = e.target.getAttribute("data-id");
  //发送axios请求
  axios({
    url: "/student/one",
    method: "get",
    //data: { 'post请求参数'},
    params: { id },
  }).then(({ data: res }) => {
    //判断业务状态码
    if (res.code == 0) {
      //姓名   年龄  手机号  期望薪资   实际薪资
      updateForm.querySelector('[name="name"]').value = res.data.name;
      updateForm.querySelector('[name="age"]').value = res.data.age;
      updateForm.querySelector('[name="phone"]').value = res.data.phone;
      updateForm.querySelector('[name="salary"]').value = res.data.salary;
      updateForm.querySelector('[name="truesalary"]').value =
        res.data.truesalary;
      // 性别
      let sexList = updateForm.querySelectorAll('[name="sex"]');
      for (let i = 0; i < sexList.length; i++) {
        //判断
        if (sexList[i].value == res.data.sex) {
          sexList[i].checked = true;
        } else {
          sexList[i].checked = false;
        }
      }
      //组   name="group"
      let groupList = updateForm.querySelectorAll('[name="group"] option');
      for (let i = 0; i < groupList.length; i++) {
        if (groupList[i].value == res.data.group) {
          groupList[i].selected = true;
        } else {
          groupList[i].selected = false;
        }
      }

      //籍贯
      //省级
      updateForm.querySelector('[name="province"]').value = res.data.province;
      //市级
      let str1 = `<option selected value="${res.data.city}">${res.data.city}</option>`;
      updateForm.querySelector('[name="city"]').innerHTML = str1;
      //县级
      let str2 = `<option selected value="${res.data.county}">${res.data.county}</option>`;
      updateForm.querySelector('[name="county"]').innerHTML = str2;

      //有个隐藏的id
      updateForm.querySelector('[name="id"]').value = res.data.id;
    }
    //成功回调
    console.log(res);
  });
});

//修改学生信息
updateForm.onsubmit = function (e) {
  //阻止表单默认跳转
  e.preventDefault();
  //发送axios
  axios({
    url: "/student/update",
    method: "PUT",
    data: $(this).serialize(),
    // params: { 'get请求参数'}
  }).then(({ data: res }) => {
    if (res.code == 0) {
      toastr.success("恭喜你修改数据成功");
      //修改成功,就要关闭对话框
      document.querySelector("#updateModal .btn-close").click();
      //刷新页面
      initStuList();
    }
    //成功回调
    // console.log(res);
  });
};
